<template>
<div>
<!-- 面包屑导航区域 -->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
  </el-breadcrumb>

  <!-- 卡片视图 界面列表 -->
  <el-card>

    <el-row>
      <el-col>
        <el-button type="primary">添加角色</el-button>
      </el-col>
    </el-row>

    <!-- 角色列表 -->
    <el-table :data="rolelist" border stripe>
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template  slot-scope="scope">
          <!-- 是顶部第一个，自动加上划线 -->
          <el-row :class="['bdbottom', i1 ===0 ? 'bdtop' : '' , 'vcenter' ]"
          v-for="(item1,i1) in scope.row.children" :key="item1.id">
            <!-- 渲染一级 -->
            <el-col :span="5">
              <el-tag closable @close="removeRightById(scope.row,item1.id)">
                {{item1.authName}}</el-tag>
              <!-- 图标 -->
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 渲染二级和三级 -->
            <el-col :span="19">
              <!-- 用fv-or嵌套渲染 -->
              <el-row :class="[i2 === 0 ? '' : 'bdtop' , 'vcenter']"
              v-for="(item2, i2) in item1.children" :key="item2.id"
              @click="removeRightById(socpe.row, item2.id)">
                <el-col :span="6">
                  <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">
                    {{item2.authName}}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <!-- closable:标签删除样式 -->
                  <el-tag  type="warning" v-for="(item3) in item2.children"
                  :key="item3.id" closable
                  @close="removeRightById(scope.row, item3.id)">
                    {{item3.authName}}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
          <!-- json带格式的展开 -->
          <!-- <pre>
            {{scope.row}}
          </pre> -->
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
          <el-button size="mini"  type="danger" icon="el-icon-delete">删除</el-button>
          <el-button size="mini"  type="warning" icon="el-icon-setting"
          @click="showSetRightDialog(scope.row)" >分配权限</el-button>

        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 分配权限弹框 -->
  <el-dialog title="分配权限" :visible.sync="setRightDialogVisible"
  width="50%">

    <!-- 树形控件 default-expand-all:默认全部展开  default-checked-keys: 默认勾选的数组 ref: 树形对象-->
    <el-tree :data="rightslist" :props="treeProps" show-checkbox
    node-key="id" default-expand-all :default-checked-keys="defKeys"
    ref="treeRef">
    </el-tree>

    <span slot="footer" class="dialog-footer">
      <el-button @click="setRightDialogVisible = false">取消</el-button>
      <el-button @click="allotRinghts">确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      //  所有角色列表数据
      rolelist: [],
      // 弹框的显隐
      setRightDialogVisible: false,
      // 所有权限数据
      rightslist: [],
      // 树形控件熟悉绑定  后面为数据库字段
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点
      defKeys: [],
      // 当前即将分配权限的Id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.rolelist = res.data
      // console.log(this.rolelist)
    },
    // 根据id删除权限
    async removeRightById(role, rightId) {
      // 提示
      const confirmResult = await this.$confirm('是否删除此权限', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', // 返回confirm
        type: 'warning'
      }).catch(err => err)// 捕获取消时的异常

      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消')
      }

      // 确认删除
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // 失败
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      // 成功 刷新数据列表会使页面刷新   重新给权限ID赋值能持久页面效果
      // this.getRolesList()
      role.children = res.data
    },
    // 分配权限对话框
    async showSetRightDialog(role, rightId) {
      // 要分配权限的id
      this.roleId = role.id
      // 清空节点缓存
      this.defKeys = []
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')

      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }

      // 获取权限保存到数据
      this.rightslist = res.data

      // 获取三级节点的id     返回的数组用来刷新defKey的数据
      this.getLeafKeys(role, this.defKeys)

      this.setRightDialogVisible = true
    },
    // 通过递归形式，获取角色下所有三级权限的ID，并保存
    getLeafKeys(node, arr) {
      // 如果当前 node 节点不包含children熟悉，则都是滴三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 递归保存ID到arr后返回给leafKey
      node.children.forEach(
        item => this.getLeafKeys(item, arr)
      )
    },
    /* 角色添加权限 getCheckedKeys:返回目前选中节点的Key用数组返回
         getHalfCheckedKeys：返回目前半选中节点的key用数组返回
         ES6语法：...  展开运算符
    */
    async allotRinghts() {
      // 获取所有选择的节点拼成新数组
      const keys = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]

      // console.log(keys)
      // 数组转字符串
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`, { rids: idStr })

      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }

      this.$message.success('分配权限成功')
      // 刷新页面
      this.getRolesList()
      // 关闭卡片
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>

.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid#eee;
}

.vcenter {
  display :flex;
  align-items: center;
}
</style>
